<template>
  <el-dialog
    title="自定义AI内容编辑"
    v-model="visible"
    top="10vh"
    width="90%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-row :gutter="20">
      <el-col :span="16">
        <el-form
          ref="dataFormRef"
          :model="dataForm"
          :rules="dataFormRules"
          label-position="right"
          label-width="120px"
          v-loading="loading"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model="dataForm.title"></el-input>
            <el-button @click="aiEvent('xuxie', 'title', '标题')">AI续写</el-button>
            <el-button @click="aiEvent('fanyi', 'title', '标题')">AI英语翻译</el-button>
          </el-form-item>
          <el-form-item label="标识码" prop="code">
            <el-input v-model="dataForm.code"></el-input>
          </el-form-item>
          <el-form-item label="跳转链接" prop="url">
            <el-input v-model="dataForm.url"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" v-model="dataForm.description"></el-input>
            <el-button @click="aiEvent('xuxie', 'description', '描述')">AI续写</el-button>
            <el-button @click="aiEvent('fanyi', 'description', '描述')">AI英语翻译</el-button>
          </el-form-item>
          <el-form-item label="图片" prop="imgs">
            <div class="uploadBox">
              <el-upload
                v-model:file-list="fileList"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-change="uploadCodeClickEvent"
                :on-preview="handlePictureCardPreview"
                :on-remove="handlePictureCardDelete"
              >
                <el-icon><Plus /></el-icon>
              </el-upload>
            </div>
            <el-button type="primary" @click="clickOssEvent">从素材库选择</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8">
        <div class="dialogue">
          <div class="title">大山AI对话框</div>
          <div class="dialogueBox">
            <div class="dialogueItems">
              <div class="dialogueItem" v-for="(item, index) in aiList" :key="index">
                <SvgIcon name="ai" />
                <div class="content">
                  {{ item.content }}
                </div>
              </div>
            </div>
            <div class="aiDialog">
              <div class="btnBox">
                <el-button round size="small" @click="clearDialog">清空对话框</el-button>
                <el-button round type="primary" size="small" v-for="item in aiBtnList" :key="item.keys" @click="insertionContent(item.keys)">赋予{{ item.label }}</el-button>
              </div>
              <el-alert title="赋予AI内容的时候是最新的一条，如需其它内容，请手动复制" type="warning" :closable="false" />
              <div class="content">
                <el-input type="textarea" v-model="aiContent" placeholder="请输入内容"></el-input>
                <div class="submintBtn">
                  <el-button type="primary" :loading="aiBtnLoading" round @click="submitAiDialog">
                    <el-icon><Position /></el-icon>
                    {{ !aiBtnLoading ? '发送' : 'AI生成中' }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="updateOrCreate">确定</el-button>
    </template>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>

    <!-- 素材库 -->
    <OssWarehouse v-model="showOss" @change="enterOss"></OssWarehouse>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue'
import { UPDATE_MODEL_EVENT } from 'cm/contants'
import { Plus, Position } from '@element-plus/icons-vue'

import { updateHomeContentInfo, getHomeContentInfo, type ICreateOrUpdateHomeContent } from '@/api/home-content'
import { ElMessage } from 'element-plus'
import { 
  fileUpload,
  type OssApiResult,
  type uploadFile } from '@/api/oss'
import appConfig from '@/config/index'

import OssWarehouse from '@/components/oss/index.vue'

import { aiSocket, aiDialogSocket } from '@/utils/socket'

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  currId: {
    type: String,
    required: true,
    default: ''
  },
})

const emit = defineEmits([UPDATE_MODEL_EVENT, 'change'])

const visible = ref<boolean>(false)

const handleClose = () => {
  fileList.value = []
  submotFileList.value = []
  emit(UPDATE_MODEL_EVENT, false)
}
  const fileList = ref<Array<object>>([])
  const submotFileList = ref<Array<any>>([])
  const uploadCodeClickEvent = async (file: any) => {
    if ('image/png, image/jpeg, image/jpg'.indexOf(file.raw.type) === -1) {
      ElMessage({ type: 'error', message: '文件类型错误' })
      return false
    }
    if (file.raw.size > 1024 * 1024 * 5) {
      ElMessage({ type: 'error', message: '上传图片大小不能超过 5M' })
      return false
    }
    loading.value = true
    const formData = new FormData()
    formData.append('file', file.raw)
    formData.append('business', '首页内容')
    const res = await fileUpload(formData)
    loading.value = false
    if (res?.code === 200) {
      ElMessage({ type: 'success', message: '上传成功' });
      const data = res.data as OssApiResult[];
      const fileData = submotFileList.value as Array<any>;
      fileData.push({
        url: data[0].url,
        name: data[0].url,
        uid: file.uid as number
      })
    } else {
      ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试' })
    }
  }

const defaultForm = {
  id: '',
  title: '',
  code: '',
  url: '',
  description: '',
  imgs: ''
}
// 表单逻辑
const dataForm = ref<ICreateOrUpdateHomeContent>({ ...defaultForm })

const dataFormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  code: [{ required: true, message: '请输入标识码', trigger: 'blur' }]
}
const loading = ref<boolean>(false)
// 查询首页内容详情
const getHomeContentInfoApi = async (currId: string) => {
  loading.value = true
  const res = await getHomeContentInfo(currId)
  loading.value = false
  if (res?.code === 200) {
    dataForm.value = res.data as ICreateOrUpdateHomeContent;
    if (dataForm.value.imgs !== '') {
      let imgs = dataForm.value.imgs as string
      let imgArray: Array<string> = (<string>imgs).split(',')
      const imgArrays: Array<object> = imgArray.map((item, index) => {
        const obj = {
          uid: index,
          url: `${appConfig.api.staticUrl}${item}`,
          name: item
        }
        return obj
      })
      fileList.value = imgArrays;
      submotFileList.value = imgArrays;
    }
    
    // getHomeContentTestApi(res.data.dictType)
  }
}

// 测试查询首页内容详情
// const getHomeContentTestApi = async (dictType: string) => {
//   const res = await getHomeContentData(dictType)
//   console.log(res)
// }

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handlePictureCardPreview = (uploadFile: object) => {
  const file = uploadFile as uploadFile
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handlePictureCardDelete = (uploadFile: object) => {
  const file = uploadFile as uploadFile
  submotFileList.value = submotFileList.value.filter(item => item.uid !== file.uid);
}

watch(
  () => props.modelValue,
  async () => {
    visible.value = props.modelValue
    if (props.modelValue && props.currId) {
      await getHomeContentInfoApi(props.currId)
    }
  }
)

const dataFormRef = ref()
const updateOrCreate = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const fileImg = submotFileList.value.map(item => {
        return item.name
      })
      dataForm.value.imgs = fileImg.join(',');
      loading.value = true
      const res = await updateHomeContentInfo(dataForm.value)
      loading.value = false
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '更新成功' })
        emit('change')
        handleClose()
      } else {
        ElMessage({ type: 'error', message: res?.msg || '网络异常，请稍后重试！' })
      }
    }
  })
}

// AI方法
const aiEvent = async (type: string, key: string, msg: string) => {
  loading.value = true
  let formKey = key;

  if (dataForm.value[formKey] === '') {
    ElMessage({ type: 'error', message: `请您输入${msg}` })
    loading.value = false
    return false;
  }

  const res = await aiSocket(type, dataForm.value[formKey]);

  if (res) {
    loading.value = false;
    const aiResultData = res as any
    dataForm.value[formKey] = `${aiResultData.data}`;
  }
}

// 素材库素材回填
const showOss = ref<boolean>(false)
const clickOssEvent = () => {
  showOss.value = true
}

const enterOss = (checkList: any) => {
  fileList.value = [...fileList.value, ...checkList]
  submotFileList.value = [...submotFileList.value, ...checkList]
}

// AI对话框列表
const aiList = ref<Array<any>>([]);
const aiContent = ref<string>('');
const aiBtnLoading = ref<boolean>(false)
const aiBtnList = ref([
  {
    label: '标题',
    value: '',
    keys: 'title'
  },
  {
    label: '描述',
    value: '',
    keys: 'description'
  }
]);

// 清空AI对话框
const clearDialog = () => {
  aiList.value = []
}

// 插入AI对应值
const insertionContent = (keys: string) => {
  const value = aiBtnList.value.find(item => item.keys === keys)?.value;
  dataForm.value[keys] = value;
}

// 发送AI内容
const submitAiDialog = async () => {
  aiBtnLoading.value = true;
  const res = await aiDialogSocket(aiContent.value);
  if (res) {
    loading.value = false;
    const aiResultData = res as any
    aiList.value.push({
      content: `${aiResultData.data}`
    });
    aiBtnList.value.forEach(item => {
      item.value = `${aiResultData.data}`
    })
    aiBtnLoading.value = false;
  }
  
}
</script>
